import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:travel/utils/colors.dart';
import 'package:travel/utils/styles.dart';
import 'package:travel/utils/tools.dart';
import 'package:travel/screen/flutter_screenutil.dart';

class TicketHistoryController extends GetxController with GetTickerProviderStateMixin {
  late TabController tabController;

  RxList<String> tabs = RxList(['已使用', '已过期']);

  @override
  void onInit() {
    int index = 0;
    if (Get.arguments != null) {
      index = Get.arguments['index'];
    }
    tabController = TabController(length: tabs.length, vsync: this, initialIndex: index);
    super.onInit();
  }

  @override
  void onClose() {
    tabController.dispose();
    super.onClose();
  }
}

class TicketHistoryView extends GetView<TicketHistoryController> {
  const TicketHistoryView({super.key});

  @override
  Widget build(BuildContext context) {
    return Obx(() => Scaffold(
          backgroundColor: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF7f7),
          appBar: AppBar(
            backgroundColor: Colors.white,
            automaticallyImplyLeading: true,
            leading: InkWell(
              onTap: () {
                Get.back();
              },
              child: Icon(
                Icons.arrow_back_ios,
                color: ColorsUtils.parseColorFromHexString(ColorsUtils.color3333),
                size: 20.w,
              ),
            ),
            leadingWidth: 40.w,
            title: Center(
              child: Text('历史券',
                  style: StylesUtils.customTextStyle(
                      color: ColorsUtils.color3333, fontSize: 18.sp, fontWeight: FontWeight.bold)),
            ),
            actions: [
              SizedBox(
                width: 40.w,
              )
            ],
            bottom: bottom,
          ),
          body: TabBarView(
            controller: controller.tabController,
            children: const [TicketUsed(), TicketExpired()],
          ),
        ));
  }

  PreferredSize get bottom {
    return PreferredSize(
      preferredSize: Size.fromHeight(40.h),
      child: Container(
        alignment: Alignment.centerLeft,
        child: ToolsUtils.getClientTabBar(controller.tabs, controller.tabController,
            isScrollable: false, indicatorSize: TabBarIndicatorSize.tab, onTap: (int index) {}),
      ),
    );
  }
}

class TicketUsed extends StatefulWidget {
  const TicketUsed({super.key});

  @override
  State<TicketUsed> createState() => _TicketUsedState();
}

class _TicketUsedState extends State<TicketUsed> {
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      padding: EdgeInsets.symmetric(horizontal: 15.w),
      child: const Column(
        children: [
          UsedRedEnvelope(
            isOpen: false,
          ),
          UsedFullReduction(
            isOpen: false,
          )
        ],
      ),
    );
  }
}

/// 使用券 新人红包
class UsedRedEnvelope extends StatefulWidget {
  final bool isOpen;

  final String imgName;

  final void Function(bool result)? onToggleCollapsed;

  const UsedRedEnvelope(
      {super.key, required this.isOpen, this.onToggleCollapsed, this.imgName = 'used.png'});

  @override
  State<UsedRedEnvelope> createState() => _UsedRedEnvelopeState();
}

class _UsedRedEnvelopeState extends State<UsedRedEnvelope> with TickerProviderStateMixin {
  late bool isOpen;

  late AnimationController animationController;
  late AnimationController controller;
  late Animation<Offset> offset;

  @override
  void initState() {
    isOpen = widget.isOpen;
    animationController = AnimationController(duration: const Duration(seconds: 2), vsync: this);
    controller = AnimationController(duration: const Duration(milliseconds: 300), vsync: this);
    offset = Tween(
      begin: const Offset(0, -0.06),
      end: Offset.zero,
    ).animate(
      CurvedAnimation(
        parent: controller,
        curve: Curves.fastOutSlowIn,
      ),
    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 10.h),
      alignment: Alignment.center,
      child: SizedBox(
        width: 345,
        child: Column(
          children: [
            Container(
              height: 120,
              decoration:
                  BoxDecoration(borderRadius: BorderRadius.circular(10.w), color: Colors.white),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    width: 90,
                    decoration: BoxDecoration(
                        color: ColorsUtils.rgba(228, 228, 228, 1),
                        borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(10.w), bottomLeft: Radius.circular(10.w))),
                    child: Column(
                      children: [
                        Container(
                          padding: EdgeInsets.only(top: 30.h),
                          alignment: Alignment.center,
                          child: Text(
                            '无门槛',
                            style: StylesUtils.customTextStyle(fontSize: 12.sp),
                          ),
                        ),
                        Container(
                          height: 58,
                          alignment: Alignment.center,
                          child: Text.rich(TextSpan(children: [
                            TextSpan(
                                text: '5',
                                style: StylesUtils.customTextStyle(
                                    fontWeight: FontWeight.w700, fontSize: 36.sp)),
                            TextSpan(
                                text: ' 元', style: StylesUtils.customTextStyle(fontSize: 12.sp))
                          ])),
                        )
                      ],
                    ),
                  ),
                  Expanded(
                      child: Stack(
                    children: [
                      Positioned(
                          top: 0,
                          right: 0,
                          child: ToolsUtils.image(widget.imgName,
                              width: 80, height: 65, fit: BoxFit.fill)),
                      Container(
                          padding: EdgeInsets.only(left: 10.w),
                          child: Column(
                            children: [
                              Container(
                                  height: 45.h,
                                  alignment: Alignment.centerLeft,
                                  child: Text(
                                    '新人红包奖励',
                                    style: StylesUtils.customTextStyle(
                                        color: ColorsUtils.color3333,
                                        fontSize: 16.sp,
                                        fontWeight: FontWeight.w700),
                                  )),
                              Container(
                                alignment: Alignment.centerLeft,
                                padding: EdgeInsets.symmetric(vertical: 5.w),
                                child: Text(
                                  '每订单立减5元；优惠券仅限本人使用，不可转赠或出售给他人',
                                  style: StylesUtils.customTextStyle(
                                      color: ColorsUtils.color6666,
                                      fontSize: 12.sp,
                                      lineHeight: 1.4.h),
                                ),
                              ),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    '长期有效',
                                    style: StylesUtils.customTextStyle(
                                        color: ColorsUtils.color9999, fontSize: 12.sp),
                                  ),
                                  InkWell(
                                    onTap: _toggleCollapsed,
                                    child: Text.rich(TextSpan(children: [
                                      TextSpan(
                                          text: '详细说明',
                                          style: StylesUtils.customTextStyle(
                                              color: ColorsUtils.color9999, fontSize: 12.sp)),
                                      WidgetSpan(
                                          child: Icon(
                                            isOpen
                                                ? Icons.keyboard_arrow_up
                                                : Icons.keyboard_arrow_down,
                                            color: ColorsUtils.parseColorFromHexString(
                                              ColorsUtils.color9999,
                                            ),
                                            size: 10.sp,
                                          ),
                                          alignment: PlaceholderAlignment.middle)
                                    ])),
                                  )
                                ],
                              )
                            ],
                          )),
                    ],
                  ))
                ],
              ),
            ),
            isOpen
                ? SlideTransition(
                    position: offset,
                    child: Container(
                      padding: const EdgeInsets.only(top: 20, left: 15, right: 15, bottom: 12),
                      child: Column(
                        children: [
                          Container(
                            alignment: Alignment.centerLeft,
                            child: Text(
                              '1、适用于温泉主题旅游景点，仅限预订自领券日起45天内的订单。',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color6666, fontSize: 12.sp, lineHeight: 1.4.h),
                            ),
                          ),
                          Container(
                            alignment: Alignment.centerLeft,
                            padding: EdgeInsets.symmetric(vertical: 5.h),
                            child: Text(
                              '2、仅限领取后7天内使用，过期自动失效。',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color6666, fontSize: 12.sp, lineHeight: 1.4.h),
                            ),
                          ),
                          Container(
                            alignment: Alignment.centerLeft,
                            child: Text(
                              '3、2024-11-01 至 2025-03-31期间，每位中国大陆手机号的用户每7天权限领取一次该优惠券，领券后7天如未使用（最晚有效期至 2025-03-31），可再次参与活动领取（库存有限，实际以页面展示为准）；若使用并下单，活动期内则不可再次领取该券。整个活动期间，同一手机号仅限使用该券一次。',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color6666, fontSize: 12.sp, lineHeight: 1.4.h),
                            ),
                          ),
                          Container(
                            alignment: Alignment.centerLeft,
                            padding: EdgeInsets.symmetric(vertical: 5.h),
                            child: Text(
                              '4、优惠券仅限本人使用，不可转赠或出售给他人。',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color6666, fontSize: 12.sp, lineHeight: 1.4.h),
                            ),
                          ),
                          Container(
                            alignment: Alignment.centerLeft,
                            child: Text(
                              '5、仅限在小默旅行APP使用。',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color6666, fontSize: 12.sp, lineHeight: 1.4.h),
                            ),
                          ),
                          Container(
                            alignment: Alignment.centerLeft,
                            padding: EdgeInsets.symmetric(vertical: 5.h),
                            child: Text(
                              '6、优惠金额不提供发票。',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color6666, fontSize: 12.sp, lineHeight: 1.4.h),
                            ),
                          ),
                          Container(
                            alignment: Alignment.centerLeft,
                            child: Text(
                              '7、恶意下单、利用程序漏洞等行为，我方有权取消优惠资格。',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color6666, fontSize: 12.sp, lineHeight: 1.4.h),
                            ),
                          ),
                        ],
                      ),
                    ))
                : Container()
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    animationController.dispose();
    controller.dispose();
    super.dispose();
  }

  void _toggleCollapsed() {
    setState(() {
      switch (controller.status) {
        case AnimationStatus.completed:
          controller.forward(from: 0);
          break;
        case AnimationStatus.dismissed:
          controller.forward();
          break;
        default:
      }
      isOpen = !isOpen;
      if (widget.onToggleCollapsed != null) {
        widget.onToggleCollapsed!.call(isOpen);
      }
    });
  }
}

/// 使用券 满减
class UsedFullReduction extends StatefulWidget {
  final bool isOpen;

  final String imgName;

  final void Function(bool result)? onToggleCollapsed;

  const UsedFullReduction(
      {super.key, required this.isOpen, this.onToggleCollapsed, this.imgName = 'used.png'});

  @override
  State<UsedFullReduction> createState() => _UsedFullReductionState();
}

class _UsedFullReductionState extends State<UsedFullReduction> with TickerProviderStateMixin {
  late bool isOpen;

  late AnimationController animationController;
  late AnimationController controller;
  late Animation<Offset> offset;

  @override
  void initState() {
    isOpen = widget.isOpen;
    animationController = AnimationController(duration: const Duration(seconds: 2), vsync: this);
    controller = AnimationController(duration: const Duration(milliseconds: 300), vsync: this);
    offset = Tween(
      begin: const Offset(0, -0.06),
      end: Offset.zero,
    ).animate(
      CurvedAnimation(
        parent: controller,
        curve: Curves.fastOutSlowIn,
      ),
    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(top: 10.h),
      alignment: Alignment.center,
      child: SizedBox(
        width: 345,
        child: Column(
          children: [
            Container(
              height: 120,
              decoration:
                  BoxDecoration(borderRadius: BorderRadius.circular(10.w), color: Colors.white),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    width: 90,
                    decoration: BoxDecoration(
                        color: ColorsUtils.rgba(228, 228, 228, 1),
                        borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(10.w), bottomLeft: Radius.circular(10.w))),
                    child: Column(
                      children: [
                        Container(
                          margin: EdgeInsets.only(top: 30.h),
                          alignment: Alignment.center,
                          child: Text(
                            '满100元可用',
                            style: StylesUtils.customTextStyle(fontSize: 12.sp),
                          ),
                        ),
                        Container(
                          height: 58,
                          alignment: Alignment.center,
                          child: Text.rich(TextSpan(children: [
                            TextSpan(
                                text: '5',
                                style: StylesUtils.customTextStyle(
                                    fontWeight: FontWeight.w700, fontSize: 36.sp)),
                            TextSpan(
                                text: ' 元', style: StylesUtils.customTextStyle(fontSize: 12.sp))
                          ])),
                        )
                      ],
                    ),
                  ),
                  Expanded(
                      child: Stack(
                    children: [
                      Positioned(
                          top: 0,
                          right: 0,
                          child: ToolsUtils.image(widget.imgName,
                              width: 80, height: 65, fit: BoxFit.fill)),
                      Container(
                          padding: EdgeInsets.only(left: 10.w),
                          child: Column(
                            children: [
                              Container(
                                height: 45.h,
                                alignment: Alignment.centerLeft,
                                child: Text(
                                  '冬日暖阳满减券',
                                  style: StylesUtils.customTextStyle(
                                      color: ColorsUtils.color3333,
                                      fontSize: 16.sp,
                                      fontWeight: FontWeight.w700),
                                ),
                              ),
                              Container(
                                alignment: Alignment.centerLeft,
                                padding: EdgeInsets.symmetric(vertical: 5.w),
                                child: Text(
                                  '周六周日福利日，温泉主题旅游尊享满100元减5元优惠',
                                  style: StylesUtils.customTextStyle(
                                      color: ColorsUtils.color6666,
                                      fontSize: 12.sp,
                                      lineHeight: 1.4.h),
                                ),
                              ),
                              Row(
                                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    '2024.11.01 - 2025.03.31',
                                    style: StylesUtils.customTextStyle(
                                        color: ColorsUtils.color9999, fontSize: 12.sp),
                                  ),
                                  InkWell(
                                    onTap: _toggleCollapsed,
                                    child: Text.rich(TextSpan(children: [
                                      TextSpan(
                                          text: '详细说明',
                                          style: StylesUtils.customTextStyle(
                                              color: ColorsUtils.color9999, fontSize: 12.sp)),
                                      WidgetSpan(
                                          child: Icon(
                                            isOpen
                                                ? Icons.keyboard_arrow_up
                                                : Icons.keyboard_arrow_down,
                                            color: ColorsUtils.parseColorFromHexString(
                                              ColorsUtils.color9999,
                                            ),
                                            size: 10.sp,
                                          ),
                                          alignment: PlaceholderAlignment.middle)
                                    ])),
                                  )
                                ],
                              )
                            ],
                          )),
                    ],
                  ))
                ],
              ),
            ),
            isOpen
                ? SlideTransition(
                    position: offset,
                    child: Container(
                      padding: const EdgeInsets.only(top: 20, left: 15, right: 15, bottom: 12),
                      child: Column(
                        children: [
                          Container(
                            alignment: Alignment.centerLeft,
                            child: Text(
                              '1、适用于温泉主题旅游景点，仅限预订自领券日起45天内的订单。',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color6666, fontSize: 12.sp, lineHeight: 1.4.h),
                            ),
                          ),
                          Container(
                            alignment: Alignment.centerLeft,
                            padding: EdgeInsets.symmetric(vertical: 5.h),
                            child: Text(
                              '2、仅限领取后7天内使用，过期自动失效。',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color6666, fontSize: 12.sp, lineHeight: 1.4.h),
                            ),
                          ),
                          Container(
                            alignment: Alignment.centerLeft,
                            child: Text(
                              '3、2024-11-01 至 2025-03-31期间，每位中国大陆手机号的用户每7天权限领取一次该优惠券，领券后7天如未使用（最晚有效期至 2025-03-31），可再次参与活动领取（库存有限，实际以页面展示为准）；若使用并下单，活动期内则不可再次领取该券。整个活动期间，同一手机号仅限使用该券一次。',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color6666, fontSize: 12.sp, lineHeight: 1.4.h),
                            ),
                          ),
                          Container(
                            alignment: Alignment.centerLeft,
                            padding: EdgeInsets.symmetric(vertical: 5.h),
                            child: Text(
                              '4、优惠券仅限本人使用，不可转赠或出售给他人。',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color6666, fontSize: 12.sp, lineHeight: 1.4.h),
                            ),
                          ),
                          Container(
                            alignment: Alignment.centerLeft,
                            child: Text(
                              '5、仅限在小默旅行APP使用。',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color6666, fontSize: 12.sp, lineHeight: 1.4.h),
                            ),
                          ),
                          Container(
                            alignment: Alignment.centerLeft,
                            padding: EdgeInsets.symmetric(vertical: 5.h),
                            child: Text(
                              '6、优惠金额不提供发票。',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color6666, fontSize: 12.sp, lineHeight: 1.4.h),
                            ),
                          ),
                          Container(
                            alignment: Alignment.centerLeft,
                            child: Text(
                              '7、恶意下单、利用程序漏洞等行为，我方有权取消优惠资格。',
                              style: StylesUtils.customTextStyle(
                                  color: ColorsUtils.color6666, fontSize: 12.sp, lineHeight: 1.4.h),
                            ),
                          ),
                        ],
                      ),
                    ))
                : Container()
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    animationController.dispose();
    controller.dispose();
    super.dispose();
  }

  void _toggleCollapsed() {
    setState(() {
      switch (controller.status) {
        case AnimationStatus.completed:
          controller.forward(from: 0);
          break;
        case AnimationStatus.dismissed:
          controller.forward();
          break;
        default:
      }
      isOpen = !isOpen;
      if (widget.onToggleCollapsed != null) {
        widget.onToggleCollapsed!.call(isOpen);
      }
    });
  }
}

/// 过期券
class TicketExpired extends StatefulWidget {
  const TicketExpired({super.key});

  @override
  State<TicketExpired> createState() => _TicketExpiredState();
}

class _TicketExpiredState extends State<TicketExpired> {
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      padding: EdgeInsets.symmetric(horizontal: 15.w),
      child: const Column(
        children: [
          UsedRedEnvelope(
            isOpen: false,
            imgName: 'expired.png',
          ),
          UsedFullReduction(
            isOpen: false,
            imgName: 'expired.png',
          )
        ],
      ),
    );
  }
}
